package com.ncmmall.mall.controller.business.goods;

import com.ncmmall.application.business.goods.GoodsChannelApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author tongchun
 * 类目配置
 */
@Controller
@RequestMapping(value = "/mall/goods/channel")
public class GoodsChannelController {

    private final static Logger logger = LoggerFactory.getLogger(GoodsChannelController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsChannelApplication channelApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 加载角色类目
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String navigation(Model model) {

        List<GoodsChannel> result = queryChannelService.findAll("select n from GoodsChannel n where n.parent = null and deleteStatus = 0 ", GoodsChannel.class);
        JSONArray nodes = new JSONArray();
        for (GoodsChannel topChannel : result) {

            JSONObject item = new JSONObject();
            item.put("id", String.valueOf(topChannel.getId()));
            item.put("title", topChannel.getName());
            item.put("feijinIcon", "");
            item.put("lever", topChannel.getLevel());

            List<GoodsChannel> children = topChannel.getChildren();
            JSONArray childNodes = new JSONArray();
            for (GoodsChannel middenChannel : children) {

                if (middenChannel.getDeleteStatus() != 0) {
                    continue;
                }

                JSONObject childItem = new JSONObject();
                childItem.put("id", String.valueOf(middenChannel.getId()));
                childItem.put("title", middenChannel.getName());
                childItem.put("feijinIcon", "");
                childItem.put("lever", middenChannel.getLevel());

                List<GoodsChannel> bottomChildren = middenChannel.getChildren();
                JSONArray bottomChildNodes = new JSONArray();
                for (GoodsChannel bottomChannel : bottomChildren) {

                    if (bottomChannel.getDeleteStatus() != 0) {
                        continue;
                    }

                    JSONObject bottomChildItem = new JSONObject();
                    bottomChildItem.put("id", String.valueOf(bottomChannel.getId()));
                    bottomChildItem.put("title", bottomChannel.getName());
                    bottomChildItem.put("feijinIcon", "");
                    bottomChildItem.put("lever", bottomChannel.getLevel());

                    bottomChildNodes.add(bottomChildItem);
                }
                childItem.put("children", bottomChildNodes);

                childNodes.add(childItem);
            }

            item.put("children", childNodes);
            nodes.add(item);

        }

        model.addAttribute("navigation", nodes.toString());

        return "mall/goods/channel/list";
    }

    /**
     * 添加子类目页面
     */
    @RequestMapping(value = "/{id}/create", method = RequestMethod.GET)
    private String createChild(Model model, @PathVariable("id") long id) {
        GoodsChannel channel = new GoodsChannel();
        channel.setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(id), GoodsChannel.class));
        model.addAttribute("_method", "POST").addAttribute("goodsChannel", channel);
        return "mall/goods/channel/form";
    }

    /**
     * 添加子类目
     */
    @RequestMapping(value = "/{id}/create", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> createChild(HttpServletRequest request, GoodsChannel channel) {
        try {
            channelApplication.createChildrenChannel(channel);
            logApplication.eventOfSystem(Securitys.currentUser(), "添加商品分类", Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            return ImmutableMap.of("status", false, "message", "添加子类目异常");
        }
    }

    /**
     * 添加一级类目页面
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private String create(Model model) {
        GoodsChannel channel = new GoodsChannel();
        model.addAttribute("_method", "POST").addAttribute("goodsChannel", channel);

        return "mall/goods/channel/form";
    }

    /**
     * 添加一级类目
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> create(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, GoodsChannel channel) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }
            String name = channel.getName();
            int count = queryChannelService.selectCount("select count(*) from mall_goods_channel where level = 1 and name = :name and deleteStatus = 0",
                    ImmutableMap.of("name", name));
            if (count > 0) {
                return ImmutableMap.of("status", false, "message", "类目名称已存在");
            }

            channelApplication.createTopChannel(channel);
            logApplication.eventOfSystem(Securitys.currentUser(), "添加商品分类", Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[添加商品类目异常]", e);
            return ImmutableMap.of("status", false);

        }

    }

    /**
     * 编辑类目页面
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.GET)
    private String modify(Model model, @PathVariable("id") long id) {

        GoodsChannel channel = queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(id), GoodsChannel.class);

        if (channel.getLevel() == 3) {
            List<GoodsChannel> channels = queryChannelService.findAll("select n from GoodsChannel n where n.parent is null  and deleteStatus = 0 ", GoodsChannel.class);
            model.addAttribute("channels", channels);
        }

        model.addAttribute("_method", "PUT").addAttribute("goodsChannel", channel);

        return "mall/goods/channel/form";
    }


    /**
     * 修改类目
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, GoodsChannel channel) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            channelApplication.modify(channel);
            logApplication.eventOfSystem(Securitys.currentUser(), "修改商品分类", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            logger.error("[修改商品类目异常]", e);
            return ImmutableMap.of("status", false, "message", "修改类目异常");
        }
    }

    /**
     * 修改子类目页面跳转
     */
    @RequestMapping(value = "/{id}/editChild", method = RequestMethod.GET)
    private String editChild(Model model, @PathVariable("id") long id) {
        GoodsChannel channel = queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(id), GoodsChannel.class);

        model.addAttribute("_method", "PUT").addAttribute("goodsChannel", channel);

        return "mall/goods/channnel/form";
    }


    /**
     * 修改子类目
     */
    @RequestMapping(value = "/{id}/editChild", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> editChild(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, GoodsChannel channel) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            channelApplication.modify(channel);
            logApplication.eventOfSystem(Securitys.currentUser(), "修改商品分类", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[修改商品类目异常]", e);
            return ImmutableMap.of("status", false);

        }
    }

    /**
     * 删除类目
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    private Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            GoodsChannel channel = queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(id), GoodsChannel.class);

            channelApplication.remove(channel);
            logApplication.eventOfSystem(Securitys.currentUser(), "删除商品分类", Securitys.getIp(request));

        } catch (Exception e) {
            logger.error("[权限删除异常]", e);
            return ImmutableMap.of("status", false);
        }

        return ImmutableMap.of("status", true);

    }

    @RequestMapping(value = "/childChannels", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> middleChannels(@RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            Map<String, Object> data = Maps.newHashMap();
            data.put("result", queryChannelService.findAll(QGoodsChannel.goodsChannel.parent.id.eq(id).and(QGoodsChannel.goodsChannel.deleteStatus.eq(0)), GoodsChannel.class));
            data.put("status", true);

            return data;

        } catch (Exception e) {
            logger.error("[查询二级分类异常:]", e);
            return ImmutableMap.of("status", false);
        }
    }


}
